﻿//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：DownPacked
// *描述：
// *?2021 MYJL . All rights reserved.
//* ======================================================================
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using System.Collections.Generic;
using UnityEditor.Compilation;

namespace HDMCode.FrameEditor 
{
    public class HDMEditorHome
    {
        [HDMEditorMenu("", "主页", "BackHome.png")]
        public static void DrewHome()
        {
            DrawMianHead();
            DrawTheme();
            DrameEnvironment();
            DrawSetupPacked();
        }


        #region 绘制头部
        /// <summary>
        /// 绘制头部
        /// </summary>
        private static void DrawMianHead()
        {
            HDMEditorHelper.DrawSettingIcon(() => 
            {
                HDMEditorMenuItem.CreatSetting<HDMEditorSetting>(HDMEditorDate.PackedProjectPath, HDMEditorDate.PackedAssetsPath);
            });

            GUILayout.Space(-2);
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(60);
                GUILayout.FlexibleSpace();
                GUILayout.Label("HDM框架管理系统 v2", HDMEditorStyle.styleTile, GUILayout.Width(210), GUILayout.Height(40));
                GUILayout.FlexibleSpace();
                
                if ( GUILayout.Button("?",GUILayout.Height(25),GUILayout.Width(25)) )
                    Application.OpenURL("https://gitee.com/haidaomao/HDMPackage");

                GUILayout.Space(30);
            }

            using (new GUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                HDMEditorHelper.DrawBox("", "PluginIcon.png", HDMEditorStyle.styleTile , GUILayout.Width(190), GUILayout.Height(93));
                GUILayout.FlexibleSpace();
            }
            
        }
        #endregion

        #region 绘制主题
        /// <summary>
        /// 绘制主题
        /// </summary>
        private static void DrawTheme()
        {
            HDMEditorHelper.DrawTileLable("主题修改");
            GUILayout.Space(5);
            using (new GUILayout.HorizontalScope())
            {
                GUILayout.Space(20);
                GUILayout.Label("主题颜色：", HDMEditorStyle.styleContent, GUILayout.Width(80), GUILayout.Height(20));
                HDMEditorStyle._supportedThemeColor = UnityEditor.EditorGUILayout.ColorField(HDMEditorStyle._supportedThemeColor, GUILayout.Width(50), GUILayout.Height(20));
                GUILayout.Space(100);
                GUILayout.Label("文字颜色：", HDMEditorStyle.styleContent, GUILayout.Width(80), GUILayout.Height(20));
                HDMEditorStyle._supportedTextColor = UnityEditor.EditorGUILayout.ColorField(HDMEditorStyle._supportedTextColor, GUILayout.Width(50), GUILayout.Height(20));
            }
        }
        #endregion

        #region 运行环境
        public static void DrameEnvironment()
        {
            HDMEditorHelper.DrawTileLable("运行环境");
            GUILayout.Space(5);
            using (new GUILayout.VerticalScope())
            {
                using (new GUILayout.HorizontalScope())
                {
                    string version = Application.unityVersion.Split('.')[0];
                    bool checkVersion = version == "2021" ? true : false;
                    DrawCheckLabel("管理系统Unity版本支持:", checkVersion);
                }

                using (new GUILayout.HorizontalScope())
                {
                    bool checkVersion = GraphicsSettings.defaultRenderPipeline;
                    DrawCheckLabel("检测插件URP环境：", checkVersion);
                }
            }
        }
        #endregion

        #region 包体安装管理

        static Vector2 previewScroll;

        public static void DrawSetupPacked()
        {
            HDMEditorHelper.DrawTileLable("安装环境");
            GUILayout.Space(5);
            using (new GUILayout.VerticalScope())
            {
                if (HDMEditorDate.packedSetting == null)
                    return;

                previewScroll = GUILayout.BeginScrollView(previewScroll, GUILayout.ExpandWidth(true), GUILayout.Height(260));

                foreach (var item in HDMEditorDate.packedSetting.downloadPackedInfo)
                {
                    using (new GUILayout.HorizontalScope())
                    {
                        GUILayout.Space(20);
                        GUILayout.Label(item.DisplayName, HDMEditorStyle.styleCheckText, GUILayout.Width(300), GUILayout.Height(20));
                        DownProgress downProgress = new DownProgress();

                        if (item.isInstall == true)
                        {
                            HDMEditorHelper.DrawButton("移除", "Remove.png", new[] { GUILayout.Height(25) }, () =>
                            {
                                HDMEditorPackManager.RemovePackage(item.packageName, () =>
                                 {
                                     UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation();
                                     item.isInstall = false;
                                     EditorUtility.SetDirty(HDMEditorDate.packedSetting);
                                     RemoveMacro(item.packageName);
                                     AssetDatabase.Refresh();
                                 }, () => { });
                            });
                        }
                        else
                        {
                            HDMEditorHelper.DrawButton("下载", "Download.png", new[] { GUILayout.Height(25) }, () =>
                            {
                                HDMEditorPackManager.AddPackage(item.DownURL, () =>
                                 {
                                     AddMacro(item.packageName);
                                     item.isInstall = true;
                                     EditorUtility.SetDirty(HDMEditorDate.packedSetting);
                                 }, () => 
                                 {
                                     EditorUtility.DisplayDialog("安装提示：", $"下载安装失败，请检查网络状态或稍后重试", "好的");
                                 });
                            });
                        }
                    }
                }
                GUILayout.EndScrollView();
            }
        }
#endregion


        /// <summary>
        /// 检查宏编译指令是都存在
        /// </summary>
        /// <param name="macroName"></param>
        /// <returns></returns>
        public static bool CheckMacro(string macroName)
        {
            bool result = false;
            BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
            if (buildTargetGroup == BuildTargetGroup.Unknown)
                result = true;

            string[] macro = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup).Split(';');
            foreach (var item in macro)
            {
                if (item == macroName.Replace('.', '_').Replace('-', '_'))
                    result = true;
            }
            return result;
        }

        /// <summary>
        /// 添加宏编译指令
        /// </summary>
        /// <param name="macroName"> 需要添加的宏名称 </param>
        public static void AddMacro(string macroName)
        {
            BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
            if (buildTargetGroup == BuildTargetGroup.Unknown) return;

            string[] macro = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup).Split(';');
            List<string> macroList = new List<string>(macro);

            foreach (var item in macro)
            {
                if (item == macroName.Replace('.', '_').Replace('-', '_')) return;
            }

            macroList.Add(macroName.Replace('.', '_').Replace('-', '_'));
            PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, string.Join(";", macroList.ToArray()));
            CompilationPipeline.RequestScriptCompilation();
        }


        /// <summary>
        /// 移除宏编译指令
        /// </summary>
        /// <param name="macroName"> 需要移除的宏名称 </param>
        public static void RemoveMacro(string macroName)
        {
            BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
            if (buildTargetGroup == BuildTargetGroup.Unknown) return;

            string[] macro = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup).Split(';');
            List<string> macroList = new List<string>(macro);

            foreach (var item in macro)
            {
                if (item == macroName.Replace('.', '_').Replace('-', '_'))
                    macroList.Remove(item);
            }

            PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, string.Join(";", macroList.ToArray()));
            CompilationPipeline.RequestScriptCompilation();
        }

        /// <summary>
        /// 绘制运行环境检查GUI
        /// </summary>
        /// <param name="muenName"> 检查菜单名称 </param>
        /// <param name="state"> 检查状态 </param>
        private static void DrawCheckLabel(string muenName, bool state)
        {
            GUILayout.Space(20);
            GUILayout.Label(muenName, HDMEditorStyle.styleCheckText, GUILayout.Width(300), GUILayout.Height(20));

            if (state)
                HDMEditorHelper.DrawLable("", "CorrectIcon.png", HDMEditorStyle.styleContent, GUILayout.Width(35), GUILayout.Height(20));
            else
                HDMEditorHelper.DrawLable("", "ErrorIcon.png", HDMEditorStyle.styleContent, GUILayout.Width(35), GUILayout.Height(20));
        }

    }
}
